﻿using Developer.Core.FrameWork.GlobalVar;
using Developer.Core.FrameWork.HelpFile;
using Microsoft.AspNetCore.Http;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Developer.Core.FrameWork.IPLimit
{
    /// <summary>
    /// IP请求日志记录中间件
    /// </summary>
    public class IPRecordMiddleWare
    {
        private readonly RequestDelegate _next;

        public IPRecordMiddleWare(RequestDelegate next)
        {
            this._next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {

            // 1、只过滤接口
            if (httpContext.Request.Path.Value.Contains("api"))
            {
                httpContext.Request.EnableBuffering();

                // 2、将请求的http信息保存起来
                var request = httpContext.Request;

                var requestInfo = JsonConvert.SerializeObject(new
                {
                    IP = GetClientIP(httpContext),
                    Url = request.Path.ObjToString().TrimEnd('/').ToLower(),
                    DateTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"),
                    Date = DateTime.Now.ToString("yyyy-MM-dd"),
                    Week = GetWeek()
                });

                if (!string.IsNullOrWhiteSpace(requestInfo))
                {
                    // TODO: 使用日志记录

                    request.Body.Position = 0;
                }
                await this._next(httpContext);
            }
            else
            {
                await this._next(httpContext);
            }

        }

        private string GetWeek()
        {
            string week = string.Empty;
            switch (DateTime.Now.DayOfWeek)
            {
                case DayOfWeek.Monday:
                    week = "周一";
                    break;
                case DayOfWeek.Tuesday:
                    week = "周二";
                    break;
                case DayOfWeek.Wednesday:
                    week = "周三";
                    break;
                case DayOfWeek.Thursday:
                    week = "周四";
                    break;
                case DayOfWeek.Friday:
                    week = "周五";
                    break;
                case DayOfWeek.Saturday:
                    week = "周六";
                    break;
                case DayOfWeek.Sunday:
                    week = "周日";
                    break;
                default:
                    week = "N/A";
                    break;
            }
            return week;
        }

        public static string GetClientIP(HttpContext context)
        {
            var ip = context.Request.Headers["X-Forwarded-For"].ObjToString();
            if (string.IsNullOrEmpty(ip))
            {
                ip = context.Connection.RemoteIpAddress.ObjToString();
            }
            return ip;
        }
    }
}
